/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include <string>
#include <cstdio>
#include <string>
#include <iostream>
#include <exception>
#include <unistd.h>
#include "BackintTool.h"
#include "BackintConst.h"
#include "log/Log.h"
#include "common/Path.h"
#include "common/File.h"
#include "config_reader/ConfigIniReader.h"

using namespace backint;

namespace {
const std::string BACKINT_LOG_NAME = "backint.log";
}
void InitLog(std::string &current)
{
    std::string currentPath = current + "/opbackint";
    std::string logPath = current + "/opbackint";
    // 初始化日志模块
    Module::CPath::GetInstance().Init(logPath);
    uint32_t iLogLevel = Module::ConfigReader::getInt("General", "LogLevel");
    uint32_t iLogCount = Module::ConfigReader::getInt("General", "LogCount");
    uint32_t iLogMaxSize = Module::ConfigReader::getInt("General", "LogMaxSize");
    Module::CLogger::GetInstance().Init(
        BACKINT_LOG_NAME.c_str(), currentPath, 0, iLogCount, iLogMaxSize);
}

uint32_t CreateLogConf(std::string &currentPath)
{
    std::string confPath = currentPath + "/conf";
    if (!Module::CFile::DirExist(confPath.c_str())) {
        if (Module::CFile::CreateDir(confPath.c_str()) != SUCCESS) {
            return 1;
        }
    }
    std::string confFile = confPath + "/hcpconf.ini";
    if (!Module::CFile::FileExist(confFile.c_str())) {
        Module::CFile::CreateFile(confPath.c_str());
        std::vector<std::vector<std::string>> confConent= {{"[General]"}, {"LogLevel=0"},
            {"LogCount=100"}, {"LogMaxSize=100"}};
        for (auto &vecs: confConent) {
            WriteOutFile(vecs, confFile);
        }
    }
    return 0;
}

int main(int argc, char** argv)
{
    std::string current = GetExeCurrentPath();
    CreateLogConf(current);
    InitLog(current);
    std::string inFileName;
    if (GetInFilePath(argc, argv, inFileName) != SUCCESS) {
        ERRLOG("Get in file path failed.");
        return FAILED;
    }
    std::string version;
    INFOLOG("Get in file path success. file path: %s", inFileName.c_str());
    if (GetVersionFromInfile(inFileName, version) != SUCCESS) {
        ERRLOG("Get version failed.");
        return FAILED;
    }
    INFOLOG("Get version success. version: %s", version.c_str());
    BackintTool *bkt = new BackintTool(version);
    if (bkt->Run(argc, argv) != SUCCESS) {
        ERRLOG("Backint running failed.");
        return FAILED;
    }
    INFOLOG("Backint running success");
    return SUCCESS;
}